package com.cgbsoft.financial.update;

import java.io.File;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.cgbsoft.financial.FinancialActivity;
import com.cgbsoft.financial.R;
import com.cgbsoft.financial.common.Global;
import com.cgbsoft.financial.model.VersionInfo;
import com.cgbsoft.financial.net.BaseAccessor;

public class UpdateApplication {
	
	private final static String TAG = "MainActivity";
	
	private static Handler handler = new Handler();
	
	
	/**
	 * 检查更新版本
	 * @author toshiba
	 *
	 */
	public static void checkVersion(final Context context) {
		final Thread thread1 = new Thread() {
			public void run() {
				try {
					Global.localVersion = context.getPackageManager().getPackageInfo(context.getPackageName(),0).versionCode; //设置本地版本号
					VersionInfo mInfo = updateSoftVersionDetail(context);
					Global.serverVersion = mInfo.getVerCode();
					Global.updateApkPath = mInfo.getDownLoadPath() + mInfo.getFileName();
					Log.i(TAG, "Global.localVersion:"+Global.localVersion);
					Log.i(TAG, "Global.serverVersion:"+Global.serverVersion);
					Log.i(TAG, "Global.updateApkPath:"+Global.updateApkPath);
					// 当前版本小于服务器版本时才提示用户更新
					if(Global.localVersion < Global.serverVersion){
						showUpdateInfo(context);
					}
					FinancialActivity.isCheckUpdate = true;
				} catch (Exception e) {
					Log.i("Main", "ee", e);
				}
			}
		};
		thread1.start();
	}
	
	/**
	 * 提示更新版本
	 */
	public static void showUpdateInfo(final Context context){
		Log.i(TAG, "checkVersion start.");
		handler.post(new Runnable() {
			public void run() {
				if(Global.localVersion < Global.serverVersion){
			        //发现新版本，提示用户更新
			        AlertDialog.Builder alert = new AlertDialog.Builder(context);
			        alert.setTitle("软件升级")
			             .setMessage("发现新版本,建议立即更新使用。")
			             .setPositiveButton("更新", new DialogInterface.OnClickListener() {
			                 public void onClick(DialogInterface dialog, int which) {
			                     //开启更新服务UpdateService
			                     //这里为了把update更好模块化，可以传一些updateService依赖的值
			                     //如布局ID，资源ID，动态获取的标题,这里以app_name为例
			                     Intent updateIntent =new Intent(context, UpdateService.class);
			                     updateIntent.putExtra("titleId",R.string.app_name);
			                     context.startService(updateIntent);
			                     Toast.makeText(context, "正在后台开启新版本下载，您可在通知栏查看进度。", Toast.LENGTH_SHORT).show();
			                 }
			             })
			             .setNegativeButton("取消",new DialogInterface.OnClickListener(){
			                 public void onClick(DialogInterface dialog, int which) {
			                     dialog.dismiss();
			                     cheanUpdateFile(context);
			                 }
			             });
			        alert.create().show();
			    }else{
			    	//清理工作
			    	cheanUpdateFile(context);
			    }
			}
		});
	    
	    Log.i(TAG, "checkVersion end.");
	}
	
	/**
	 * 自动更新接口，带升级描述
	 * @param context
	 * @return
	 * @throws JSONException
	 */
	public static VersionInfo updateSoftVersionDetail(Context context) throws JSONException{
		String urlString = Global.UPGRADE_CHECK_PATH;
		//[{"verName":1.0.1,"verCode":2}]  
		HashMap<String, String> params = new HashMap<String, String>();
		String jsonString = BaseAccessor.deRequest(context, urlString, params);
		System.out.println("jsonString="+jsonString);
		VersionInfo vinfo = new VersionInfo();
		JSONArray array = new JSONArray(jsonString); 
        if (array.length() > 0) {  
            JSONObject obj = array.getJSONObject(0);
            try {  
            	vinfo.setVerCode(Integer.parseInt(obj.getString("verCode")));
            	vinfo.setVerName(obj.getString("verName"));
            	vinfo.setVersionCharacter(obj.getString("versionCharacter"));
            	vinfo.setDownLoadPath(obj.getString("downLoadPath"));
            	vinfo.setFileName(obj.getString("fileName"));
            } catch (Exception e) {
                vinfo.setVerCode(-1);
            	vinfo.setVerName("");
            	vinfo.setVersionCharacter("");
            	vinfo.setDownLoadPath("");
            }
        }  
        return vinfo;  
	}
	
	/**
	 * 清理工作
	 */
	private static void cheanUpdateFile(final Context context) {
		//清理工作
    	File updateFile = new File(Global.downloadDir, context.getResources().getString(R.string.app_name)+".apk");
    	if(updateFile.exists()){
    	   //当不需要的时候，清除之前的下载文件，避免浪费用户空间
    	   updateFile.delete(); 
    	}
	}
}